import React, { useEffect, useState } from 'react';
import { Drawer, Form, Input, Button, notification } from 'antd';
import { fetchApi } from '../../general/api';
import SelectControllers from '../alert/alarm_config_group_select';

interface AppConfigDrawerProps {
    alarm_config_tmp_codes: string;
    isOpen: boolean; // 明确指定 isOpen 为 boolean 类型  
    appName: string; // 确保 appName 也是 string  
    onClose: () => void; // 关闭抽屉的回调  
}

// 定义表单值的类型  
interface FormValues {
    alarm_config_group_id: string;
    app_now_status_alarm_config?: string; // 加上问号表示可选  
    app_cpu_alarm_config?: string; // 加上问号表示可选  
    app_mem_alarm_config?: string; // 加上问号表示可选  
    app_disk_alarm_config?: string; // 加上问号表示可选  
    app_link_alarm_config?: string; // 加上问号表示可选  
}

// 定义动态索引类型  
type NewFormValues = {
    [key: string]: string | undefined; // 允许任何字符串作为索引，值可以是 string 或 undefined  
};

const AppProbeCreateDrawer: React.FC<AppConfigDrawerProps> = ({ isOpen, appName, onClose, alarm_config_tmp_codes }) => {
    const [form] = Form.useForm();
    const [alarmConfigGroupCode, setAlarmConfigGroupCode] = useState<string>(''); // 用于存储选中的控制器ID  

    useEffect(() => {
        const fetchData = async () => {
            if (!appName || !alarmConfigGroupCode) return; // 确保 alarmConfigGroupCode 存在  
            try {
                // 包含 alarm_config_group_id 到查询参数中  
                const response = await fetchApi(`/easymonitor/api/probe_tmp?app_name=${appName}&alarm_config_group_id=${alarmConfigGroupCode}&alarm_config_tmp_codes=${alarm_config_tmp_codes}`, { method: 'GET' });

                // 确保 response 是数组且不为空  
                if (Array.isArray(response) && response.length > 0) {
                    const data = response; // 用于遍历的返回值数组  

                    // 使用动态索引类型初始化 newFormValues   
                    const newFormValues: NewFormValues = {};

                    // 遍历返回数据，填充对应的表单项  
                    data.forEach(item => {
                        if (item.alarm_config_tmp_code) {
                            newFormValues[item.alarm_config_tmp_code] = item.alarm_config_tmp_formula; // 设置每个对应的值  
                        }
                    });

                    form.setFieldsValue(newFormValues); // 设定填充后的值  
                } else {
                    notification.warning({ message: '没有数据', description: '未找到相关配置', duration: 2 });
                }
            } catch (error) {
                notification.error({ message: '请求失败', description: `获取数据失败: ${error}`, duration: 2 });
            }
        };

        if (isOpen) {
            fetchData();
        }
    }, [appName, isOpen, alarmConfigGroupCode, form, alarm_config_tmp_codes]);

    // 处理选择控制器时更新 alarm_config_group_code  
    const handleCityChange = (value: string, label: string, alarmConfigGroupCode: string) => {
        form.setFieldsValue({ alarm_config_group_id: value });
        setAlarmConfigGroupCode(value); // 更新 alarm_config_group_code  
    };

    const handleConfirm = async () => {
        try {
            const values = await form.validateFields();
            await fetchApi('/easymonitor/api/probe', { method: 'POST', body: JSON.stringify(values) });
            notification.success({ message: '提交成功', description: '数据已更新', duration: 2 });
            onClose();
        } catch (error) {
            notification.error({ message: '提交失败', description: `错误: ${error}`, duration: 2 });
        }
    };

    return (
        <Drawer title="新建应用探针" placement="right" width={500} onClose={onClose} open={isOpen}>
            <Form form={form} layout="vertical">
                <Form.Item
                    label="控制器绑定"
                    name="alarm_config_group_id"
                    rules={[{ required: true, message: '请绑定一个控制器' }]}>
                    <SelectControllers
                        selectedCity={form.getFieldValue('alarm_config_group_id') || ''} // 直接从 form 获取  
                        onCityChange={handleCityChange}
                        style={{ width: '100%' }}
                    />
                </Form.Item>
                <Form.Item label="应用当前状态" name="app_now_status_alarm_config">
                    <Input.TextArea />
                </Form.Item>
                <Form.Item label="CPU 指标" name="app_cpu_alarm_config">
                    <Input.TextArea />
                </Form.Item>
                <Form.Item label="内存指标" name="app_mem_alarm_config">
                    <Input.TextArea />
                </Form.Item>
                <Form.Item label="硬盘指标" name="app_disk_alarm_config">
                    <Input.TextArea />
                </Form.Item>
                <Form.Item label="连接数指标" name="app_link_alarm_config">
                    <Input.TextArea />
                </Form.Item>
            </Form>
            <Button type="primary" onClick={handleConfirm}>确认</Button>
        </Drawer>
    );
};

export default AppProbeCreateDrawer;